<?php

namespace App\Http\Controllers;

//use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Book;
use App\Models\Bags;
use App\Models\UsersReg;
use App\Models\Category as cat;
use App\Models\Tag;
use App\Models\BooksTag;
use App\Models\Accountlog; //支付记录
use App\Models\TixianZhanghu; //提现账户信息
use Request;
use Auth;

class AdminBookController extends Controller
{
    public function index()
    {
        //每页显示15个记录
        $pre_page = 15;
        //$posts = Book::paginate($pre_page);

        //获得所有图书信息的数据->books数据库 按倒序
        $books = Book::orderBy('book_id', 'desc')->paginate($pre_page);
        
        return view('admin.abooklist', compact('books'));
    }

    public function noclass()
    {
        //显示没有归类的图书
        //每页显示15个记录
        $pre_page = 15;
        //$posts = Book::paginate($pre_page);

        //获得所有图书信息的数据->books数据库 按倒序
        $books = Book::whereNull('cat_id')->orderBy('book_id', 'desc')->paginate($pre_page);
        
        return view('admin.abooklistnoclass', compact('books'));
    }

    public function create()
    {
        //后台添加图书

        // 图书分类名字
        $cats  = cat::all();

        return view('admin.addbook', array('cats'=> $cats));
    }

    public function store(Request $request)
    {
        //保存添加的图书
        $books = new Book;

        //判断有没有上传文件
        if($request::hasFile('fengmian'))
        {

            //取得上传文件,获得的临时文件，例如php143F.tmp
            $file = $request::file('fengmian');
            // return $file;

            //得到文件名
            //$clientName = $file -> getClientOriginalName();
        
            //得到上传文件的扩展名
            $entension = $file -> getClientOriginalExtension();
        
            //得到文件的类型 得到的结果是 image/jpeg
            //$mineType = $file -> getMimeType();
        
            // 缓存在tmp文件夹中的文件名 例如 phpD97C.tmp 这种类型的
            // $tmpName = $file ->getFileName();
        
            //这个表示的是缓存在tmp文件夹下的文件的绝对路径
            //例如 D:\wamp2.5\tmp\phpF26A.tmp
            //$realPath = $file -> getRealPath();
        
            //这里app_path()就是app文件夹所在的路径
            //$newName 可以是你通过某种算法获得的文件的名称
            //$path = $file -> move(app_path().'/uploads',$newName);

            //$dirName = 'uploads\yds1\\'; //windows 系统下目录结构
            $dirName = "uploads/yds3/"; // linux 系统下的目录结构（图片文件保存的目录）
            $filename = time(); //用时间作为文件名字

            //获得图片文件的宽度，高度，文件类型 
            list($bigWidth, $bigHeight, $bigType) = getimagesize($file);
            /* 
            $bigType: 
            1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，
            7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，
            9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，
            15 = WBMP，16 = XBM 
            */        

            if($bigWidth > 300)
            {
                $width = 300;
                $height = $bigHeight * ($width  / $bigWidth);

                // 把文件读入一个字符串
                $imagedata = file_get_contents($file);
                // 创建缩略图画板
                $block = imagecreatetruecolor($width, $height);
                // 启用混色模式
                imagealphablending($block, false);
                // 保存PNG alpha通道信息
                imagesavealpha($block, true);
                // 创建原图画板
                $bigImg = imagecreatefromstring($imagedata);
                // 缩放
                imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHeight);

                // 小图片文件名字
                $newName = 'yds' . $filename . '.' . $entension;
                // 生成临时文件名,保存到$dirName目录下,此时文件数据为空
                $tmpFilename = tempnam($dirName, 'tmp');
                // 改变文件属性
                // chmod($tmpFilename, 0644);
                // 保存图片,写数据到临时文件里
                switch ($bigType) {
                    case 1: 
                        imagegif($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 2: 
                        // 保存临时文件，写数据到临时文件里
                        imagejpeg($block, $tmpFilename);
                        // 给临时文件$tmpFilename改名为$newName，并且保存到$dirName目录下
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 3: 
                        imagepng($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
                }
                // 销毁
                imagedestroy($block);

                //图片裁剪保存完毕end

                // 保存原始图片
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path_m = $file -> move($dirName, $newName_m);
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

            }
            else {
                // 图片宽度<=300
                $newName = 'yds' . $filename . '.' . $entension;
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path = $file -> move($dirName, $newName);
                $path_m = copy($path, $dirName . $newName_m);
                $path_m = $dirName . $newName_m;
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符
            }        

            $books->bimg = $path;
            $books->bimg_m = $path_m;

        }        

        $books->book_name = trim(request::input('bookname'));
        $books->yuanzuoming = trim(request::input('yuanzuoming'));
        $books->fubiaoti = trim(request::input('fubiaoti'));
        $books->zuozhe = trim(request::input('zuozhe'));
        $books->yizhe = trim(request::input('yizhe'));
        $books->chubanshe = trim(request::input('chubanshe'));
        $books->chupinfang = trim(request::input('chupinfang'));
        $books->chubannian = trim(request::input('chubannian'));
        $books->yeshu = trim(request::input('yeshu'));
        $books->zhuangzhen = trim(request::input('zhuangzhen'));
        $books->dingjia = trim(request::input('dingjia'));
        $books->isbn = trim(request::input('isbn'));
        $books->congshu = trim(request::input('congshu'));
        $books->neirongjianjie = request::input('neirongjianjie');
        $books->zuozhejianjie = request::input('zuozhejianjie');
        $books->mulu = request::input('mulu');
        $books->cat_id = request::input('catname');
        $books->add_time = time();
        $books->last_update = time(); //获取当前时间戳

        $books->save();

        return '保存成功！<a href="caiji_douban">继续采集书籍</a>'; 

    }

    public function edit($id)
    {
        // 编辑书籍的信息
        $books = Book::find($id);
        // 图书分类名字
        $cats  = cat::all();
        // 得到本图书的分类名字
        $catname = cat::find($books->cat_id);

        // 图书的标签
        $tags = Tag::all();        

        return view('admin.ainfoedit', array('books' => $books, 'cats' => $cats, 'catname' => $catname, 'tags' => $tags));
    }

    public function update(Request $request, $id)
    {
        
        // 更新（保存编辑）书籍的信息
        $books = Book::find($id);

        //判断有没有上传文件
        if($request::hasFile('fengmian'))
        {

            if($books->bimg != null)
            {
                //删除原来上传的文件
                if(file_exists($books->bimg))
                {
                    //删除文件                    
                    unlink($books->bimg);
                }
            }

            if($books->bimg_m != null)
            {
                //删除原来上传的文件
                if(file_exists($books->bimg_m))
                {
                    //删除文件                    
                    unlink($books->bimg_m);
                }
            }

            //取得上传文件
            $file = $request::file('fengmian');
            //得到文件名
            //$clientName = $file -> getClientOriginalName();
        
            //得到上传文件的扩展名
            $entension = $file -> getClientOriginalExtension();
        
            //得到文件的类型 得到的结果是 image/jpeg
            //$mineType = $file -> getMimeType();
        
            // 缓存在tmp文件夹中的文件名 例如 phpD97C.tmp 这种类型的
            //$tmpName = $file ->getFileName();
        
            //这个表示的是缓存在tmp文件夹下的文件的绝对路径
            //例如 D:\wamp2.5\tmp\phpF26A.tmp
            //$realPath = $file -> getRealPath();
        
            //这里app_path()就是app文件夹所在的路径
            //$newName 可以是你通过某种算法获得的文件的名称
            //$path = $file -> move(app_path().'/uploads',$newName);

            //$dirName = 'uploads\yds1\\'; //windows 系统下目录结构
            $dirName = "uploads/yds3/"; // linux 系统下的目录结构（图片文件保存的目录）
            $filename = time(); //用时间作为文件名字

            //获得图片文件的宽度，高度，文件类型 
            list($bigWidth, $bigHeight, $bigType) = getimagesize($file);
            /* 
            $bigType: 
            1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，
            7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，
            9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，
            15 = WBMP，16 = XBM 
            */        

            if($bigWidth > 300)
            {
                $width = 300;
                $height = $bigHeight * ($width  / $bigWidth);

                // 把文件读入一个字符串
                $imagedata = file_get_contents($file);
                // 创建缩略图画板
                $block = imagecreatetruecolor($width, $height);
                // 启用混色模式
                imagealphablending($block, false);
                // 保存PNG alpha通道信息
                imagesavealpha($block, true);
                // 创建原图画板
                $bigImg = imagecreatefromstring($imagedata);
                // 缩放
                imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHeight);

                // 小图片文件名字
                $newName = 'yds' . $filename . '.' . $entension;
                // 生成临时文件名,保存到￥dirName目录下,此时文件数据为空
                $tmpFilename = tempnam($dirName, 'tmp');
                // 保存图片,写数据到临时文件里
                switch ($bigType) {
                    case 1: 
                        imagegif($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);                        
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 2: 
                        // 保存临时文件，写数据到临时文件里
                        imagejpeg($block, $tmpFilename);
                        // 给临时文件$tmpFilename改名为$newName，并且保存到$dirName目录下
                        // rename($tmpFilename, $dirName . $newName);  //文件属性为600
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
            
                    case 3: 
                        imagepng($block, $tmpFilename);
                        // rename($tmpFilename, $dirName . $newName);
                        copy($tmpFilename, $dirName . $newName); //为了改变文件属性为644
                        unlink($tmpFilename); //删除临时文件
                        $path = $dirName . $newName;
                        break;
                }
                // 销毁
                imagedestroy($block);

                //图片裁剪保存完毕end

                // 保存原始图片
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path_m = $file -> move($dirName, $newName_m);
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符

            }
            else {
                // 图片宽度<=300
                $newName = 'yds' . $filename . '.' . $entension;
                $newName_m = 'yds' . $filename . 'm' . '.' . $entension;
                // 获得的临时文件$file更名到$dirName目录下
                $path = $file -> move($dirName, $newName);
                copy($path, $dirName . $newName_m);
                $path_m = $dirName . $newName_m;
                //$path = str_replace('\\', '/', $path); //windows系统时 改变数据库的/字符
            }        

            $books->bimg = $path;
            $books->bimg_m = $path_m;

        }        

        $books->book_name = trim(request::input('bookname'));
        $books->yuanzuoming = trim(request::input('yuanzuoming'));
        $books->fubiaoti = trim(request::input('fubiaoti'));
        $books->zuozhe = trim(request::input('zuozhe'));
        $books->yizhe = trim(request::input('yizhe'));
        $books->chubanshe = trim(request::input('chubanshe'));
        $books->chupinfang = trim(request::input('chupinfang'));
        $books->chubannian = trim(request::input('chubannian'));
        $books->yeshu = trim(request::input('yeshu'));
        $books->zhuangzhen = trim(request::input('zhuangzhen'));
        $books->dingjia = trim(request::input('dingjia'));
        $books->isbn = trim(request::input('isbn'));
        $books->congshu = trim(request::input('congshu'));
        $books->neirongjianjie = request::input('neirongjianjie');
        $books->zuozhejianjie = request::input('zuozhejianjie');
        $books->mulu = request::input('mulu');
        $books->cat_id = request::input('catname');
        $books->last_update = time(); //获取当前时间戳

        $books->save();

        //更新书城里的 书名，作者，isbn（如果有本书籍）
        $bags = Bags::where('book_id', $id)->get(); //有多个会员出售，全部更新
        if($bags->count() > 0){
            //批量更新
            $data=['book_name' => trim(request::input('bookname')), 
                   'zuozhe' => trim(request::input('zuozhe')),
                   'isbn'   => trim(request::input('isbn'))
                   ]; 
            Bags::where('book_id', $id)->update($data);
        }

        // 保存对应的标签信息
        //$bookstag = new BooksTag;
        //$bookstag->book_id =$books->book_id;
        //$bookstag->tag_id = request::input('tagsname');

        //$bookstag->save();

        return '更新成功！'; 

    }

    public function destroy($id)
    {
        
    if (Auth::check()) 
    {
        // 删除书籍的信息
        $books = Book::find($id);
        //获得要删除的文件名字
        $picName = $books->bimg;
        if(file_exists($picName))
        {
            //删除文件
            unlink($picName);
        }

        $picName_m = $books->bimg_m;
        if(file_exists($picName_m))
        {
            //删除文件
            unlink($picName_m);
        }

        
        $books->delete();
        return $this->index();
    }

    }

    public function userslist()
    {
        //会员列表
        $pre_page = 20;
        $users = UsersReg::orderBy('uid', 'desc')->paginate($pre_page);
        //统计会员总数
        $userscount = UsersReg::get()->count();

        return view('admin.userslist', array(
            'users' => $users,
            'userscount' => $userscount
            ));
    }

    public function tixianlist(){
        //提现列表
        //20,正在提现的; 21,提现完整
        $pre_page = 15;
        $accountlogs = Accountlog::where('change_type', 20)->paginate($pre_page);

        foreach ($accountlogs as $accountlog) {
            //得到发布长评论的会员资料
            $accountlog['users'] = $accountlog->hasOnUsersReg;
        }

        foreach ($accountlogs as $accountlog) {
            //得到提现账户
            $accountlog['tixianzhanghu'] = $accountlog->hasOnetixian;
        }

        // dd($accountlogs);
        return view('admin.tixianlist', array(
            'accountlogs' => $accountlogs
            ));
    }
}
